package com.nuoniu.sibanyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.text.PinyinUtils;
import com.nuoniu.sibanyun.entity.SysArea;
import com.nuoniu.sibanyun.entity.crm.CrmCustomer;
import com.nuoniu.sibanyun.entity.dto.SysAreaDto;
import com.nuoniu.sibanyun.mapper.SysAreaMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmCustomerMapper;
import com.nuoniu.sibanyun.service.ISysAreaService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 行政区划 服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-06-04
 */
@Service
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysArea> implements ISysAreaService {

    @Autowired
    private SysAreaMapper areaMapper;
    @Autowired
    private CrmCustomerMapper crmCustomerMapper;

    @Override
    public Page<SysArea> areaPage(Page pages, SysArea area) {
        UserInfo userInfo = UserThreadLocal.get();
        SysArea sysArea = new SysArea();
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>(sysArea);
        if(StringUtils.isNotBlank(area.getAreaName())){
            queryWrapper.like("area_name", area.getAreaName());
        }else if(area.getParentCode() != null) {
            queryWrapper.eq("parent_code", area.getParentCode());
        }

        if(area.getCompanyId() != null) {
            queryWrapper.eq("company_id", area.getCompanyId());
        }else {
            queryWrapper.eq("company_id", userInfo.getCompanyId());
        }

        queryWrapper.orderByAsc("pym");
        queryWrapper.orderByAsc("tree_sort");
        Page<SysArea> page = page(pages, queryWrapper);
        return page;
    }

    @Override
    public void saveArea(SysArea area) {
        UserInfo userInfo = UserThreadLocal.get();
        area.setCompanyId(userInfo.getCompanyId());
        area.setCompanyName(userInfo.getCompanyName());
        area.setUpdateBy(userInfo.getUserId());

        //修改上级
        if(area.getParentCode() != null) {
            SysArea parentCode = areaMapper.getAreaByCode(area.getParentCode(), userInfo.getCompanyId());
            if(area.getId() != null) {
                SysArea sysArea = getById(area.getId());
                if(!(parentCode.getTreeLevel().compareTo(sysArea.getTreeLevel()) < 0)) {
                    throw new NuoNiuException("上级地区选择不合理");
                }
            }

            if(parentCode != null) {
                area.setParentCodes(parentCode.getParentCodes() + area.getParentCode() + ",");
                area.setTreeNames(parentCode.getTreeNames() + "/" + area.getAreaName());
            }
            area.setTreeLevel(parentCode.getTreeLevel() + 1);
        }else {
            area.setTreeNames(area.getAreaName());
        }

        if(area.getId() == null) {
            SysArea sysArea = areaMapper.getAreaByCode(area.getAreaCode(), userInfo.getCompanyId());
            if(sysArea != null) {
                throw new NuoNiuException("地区编码已存在");
            }

            String areaName = area.getAreaName();
            if (areaName.contains("重庆")) {
                areaName = areaName.replace("重庆", "cq");
            }

            area.setPym(PinyinUtils.getFirstSpell(areaName));
            area.setCreateBy(userInfo.getUserId());
            if(userInfo.getCompanyId() != 1) {
                area.setIsUpdate(true);
            }

            //保存
            Boolean result = save(area);
            if(result) {
                //修改父级
                areaMapper.updateLeafByCode(area.getParentCode(), userInfo.getCompanyId(), 0);
            }
        }else {
            if(userInfo.getCompanyId() != 1) {
                area.setIsUpdate(true);
            }

            //修改地区
            updateById(area);
            //同步客户地区
            crmCustomerMapper.updateAreaName(area);
        }

        if(userInfo.getCompanyId() != 1) { //修改上级状态
            area.setIsUpdate(true);
            if(area.getParentCodes() != null) {
                String[] areaCodes = area.getParentCodes().split(",");
                for(int i=0; i<areaCodes.length; i++) {
                    if(StringUtils.isNotEmpty(areaCodes[i])) {
                        areaMapper.updateAreaIsUpdate(Integer.valueOf(areaCodes[i]), userInfo.getCompanyId());
                    }
                }
            }
        }
    }

    @Override
    public void deleteArea(Long id, Integer parentCode) {
        UserInfo userInfo = UserThreadLocal.get();
        SysArea sysArea = getById(id);
        if(!sysArea.getTreeLeaf()) {
            throw new NuoNiuException("请先删除子级地区");
        }

        removeById(id);
        List<SysArea> areaList = areaMapper.getAreaByParentCode(parentCode, userInfo.getCompanyId());
        if(areaList.size() == 0) {
            areaMapper.updateLeafByCode(parentCode, userInfo.getCompanyId(), 1);
        }
    }

    @Override
    @Transactional
    public void saveAreaList(SysAreaDto area) {
        UserInfo userInfo = UserThreadLocal.get();
        if(userInfo.getCompanyId() == 1) {
            throw new NuoNiuException("系统数据，无法导入");
        }

        area.setCompanyId(userInfo.getCompanyId());
        area.setCompanyName(userInfo.getCompanyName());
        area.setCreateBy(userInfo.getUserId());
        area.setUpdateBy(userInfo.getUserId());
        //删除旧数据
//        Map param = new HashMap();
//        param.put("company_id", userInfo.getCompanyId());
//        param.put("is_update", 0);
//        areaMapper.deleteByMap(param);
        //剔除重复数据
        List<Long> areaCodes = areaMapper.getAreaByCompany(userInfo.getCompanyId(), 1);
        for(int i=0; i<areaCodes.size(); i ++) {
            area.getAreaCodes().remove(areaCodes.get(i));
        }

        //批量保存新数据
        if(area.getAreaCodes().size() > 0) {
            area.setAreaCodeStr(StringUtils.join(area.getAreaCodes(), ","));
            areaMapper.insertAll(area);
        }
    }

    @Override
    public String findAreaTreeNamesByCode(Integer areaCode, Integer companyId) {
        return baseMapper.findAreaTreeNamesByCode(areaCode, companyId);
    }

    @Override
    @Async
    public void updateCrmArea(List<CrmCustomer> customerList, Integer companyId) {
        for(CrmCustomer customer : customerList) {
            if(StringUtils.isNotBlank(customer.getAreaName())) {
                SysArea area = areaMapper.getAreaByTreeNames(customer.getAreaName(), companyId);
                if(area != null) {
                    customer.setAreaId(area.getId().intValue());
                    customer.setAreaCode(area.getAreaCode().toString());
                    customer.setAreaTreeCodes(area.getParentCodes() + area.getAreaCode());
                    crmCustomerMapper.updateById(customer);
                }
            }
        }
    }

    @Override
    public HashMap<String,String> findAreaTreeNamesById(Integer areaId, Integer companyId) {
        return areaMapper.findAreaTreeNamesById(areaId, companyId);
    }

    @Override
    public List<Map> treeList(Integer companyId) {
        if(companyId == null) {
            UserInfo userInfo = UserThreadLocal.get();
            companyId = userInfo.getCompanyId();
        }
        return areaMapper.getTreeList(companyId);
    }
}
